﻿using System;
using System.Collections.Generic;
using System.Text;
using Imps.Client.Pc;
using Imps.Client.Core;
using System.Windows.Forms;
using com.hetaoos.FetionSDK.Event;

namespace com.hetaoos.FetionSDK.Message
{
    public class SendMultiSMSControl
    {
        private FetionSDK _frameworkWin = null;

        private AsyncBizOperation op;
        private Queue<SendSMSItem> _stackSMSItems;
        private bool sending;
        private SendSMSItem _currentSendingItem;
        private List<Contact> _listContacts;
        private ContactBase _contactBase;

        public SendMultiSMSControl(FetionSDK framework, ContactBase contactBase)
        {
            _frameworkWin = framework;
            _contactBase = contactBase;
            if (this.op == null)
            {
                this.op = new AsyncBizOperation();
                this.op.Successed += new EventHandler(this.op_Successed);
                this.op.ImpsError += new EventHandler<ImpsErrorEventArgs>(this.op_ImpsError);
            }
            _stackSMSItems = new Queue<SendSMSItem>();
        }

        /// <summary>
        /// 获取好友列表,现在没有用
        /// </summary>
        /// <returns></returns>
        public string getUserList()
        {
            if (_frameworkWin == null)
            {
                return string.Empty;
            }

            lock (_frameworkWin.AccountManager.CurrentUser.ContactList.Groups.SyncRoot)
            {
                foreach (ContactGroup group in _frameworkWin.AccountManager.CurrentUser.ContactList.Groups)
                {
                    if (group.Id != -1)
                    {
                        TreeNode node = new TreeNode(group.Name);
                        node.Name = group.Id.ToString();
                        node.Checked = true;
                        node.Tag = group;
                        List<Contact> listContacts = group.Contacts.ListContacts;

                        foreach (Contact contact in listContacts)
                        {
                            if (!(contact is ChatFriend))
                            {
                                TreeNode node2 = new TreeNode(contact.DisplayName);
                                node2.Name = contact.Uri.Raw;
                                node2.Checked = true;
                                node2.Tag = contact;
                                node.Nodes.Add(node2);
                            }
                        }
                        continue;
                    }
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取当前用户
        /// </summary>
        public Imps.Client.Core.User CurrentUser
        {
            get
            {
                return _frameworkWin.AccountManager.CurrentUser;
            }
        }

        /// <summary>
        /// 发送消息成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void op_Successed(object sender, EventArgs e)
        {
            this.SendNext();
        }

        /// <summary>
        /// 发送消息失败
        /// </summary>
        private void op_ImpsError(object sender, ImpsErrorEventArgs e)
        {
            //ErrorLog.WriteLog("op_ImpsError:" + StringHelper.EncodString(e.Summary));
            this.SendNext();


            //这里要些日子
            //if (!base.IsDisposed && (e.Description == "486"))
            //{
            //    this._sendFrequent = true;
            //    this._historyChatManager.LinkButtonFont = new Font("Microsoft Sans Serif", 9.5f, FontStyle.Regular, GraphicsUnit.Point, 0);
            //    this._historyChatManager.AppentString("<font size=9.5 color=#a31515>【系统提示】: " + StringHelper.EncodString(e.Summary) + "</font>");
            //    OleKey newKey = OleKeyManager.Instance.NewKey;
            //    this._historyChatManager.AppendLink(newKey, "详细内容", "frequent");
            //    this._historyChatManager.AppendCRLF();
            //    this.txtSendContent.Enabled = false;
            //    this.txtSendContent.Enabled = false;
            //}
            //else
            //{
            //    this.SendNext();
            //}

        }
        /// <summary>
        /// 开始发送消息
        /// </summary>
        private void StartSend()
        {
            this.sending = true;
            this.SendNext();
        }

        /// <summary>
        /// 发送下一条消息
        /// </summary>
        private void SendNext()
        {
            if (this._stackSMSItems.Count > 0)
            {
                this._currentSendingItem = this._stackSMSItems.Dequeue();
                SMSManager.AsyncSendSMS(this.CurrentUser, this._currentSendingItem.Contact.Uri.Raw, this._currentSendingItem.Content, this.op);
            }
            else
            {
                this.sending = false;
                _frameworkWin.doSDK_Error(this, ErrorType.SendSMS, "短信发送完毕！");
                //if (!base.IsDisposed)
                //{
                //    this._historyChatManager.AppentString("<font size=9.5 color=95,161,1>【系统提示】:短信发送完毕！</font>");
                //    this._historyChatManager.AppendCRLF();
                //}
            }
        }


        /// <summary>
        /// 给列表中的手机号或者飞信号发送消息
        /// </summary>
        /// <param name="list"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int SendSMS(string id, string msg)
        {
            List<string> list = new List<string>();
            list.Add(id);
            return SendSMS(list, msg);
        }
        /// <summary>
        /// 给列表中的手机号或者飞信号发送消息
        /// </summary>
        /// <param name="list"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int SendSMS(List<string> list, string msg)
        {
            if (list == null || list.Count == 0)
            {
                return -1;
            }
            _listContacts = _contactBase.getAllContactList();
            int index = 0;
            if (_listContacts == null || _listContacts.Count == 0)
            {
                return -1;
            }
            List<Contact> selectedContacts = new List<Contact>();

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Length == 11)
                {
                    index = findContactByMobileNo(list[i]);
                }
                else
                {
                    index = findContactBySID(list[i]);
                }

                if (index >= 0)
                {
                    selectedContacts.Add(_listContacts[index]);
                }
                else
                {
                    //ErrorLog.WriteLog("没有找到该用户：" + list[i]);
                    _frameworkWin.doSDK_Error(this, ErrorType.SendSMS, "没有找到该用户：" + list[i]);
                }
            }

            return sendSMS_Base(ref selectedContacts, ref msg);
        }
        /// <summary>
        /// 发送消息基函数
        /// </summary>
        /// <param name="selectedContacts"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private int sendSMS_Base(ref List<Contact> selectedContacts, ref string msg)
        {
            if (selectedContacts.Count == 0)
            {
                return 0;
            }
            else
            {
                if (this.op == null)
                {
                    this.op = new AsyncBizOperation();
                    this.op.Successed += new EventHandler(this.op_Successed);
                    this.op.ImpsError += new EventHandler<ImpsErrorEventArgs>(this.op_ImpsError);
                }
                foreach (Contact contact in selectedContacts)
                {
                    if ((contact.Uri.Raw == this.CurrentUser.Uri.Raw) || contact.EnableSMS)
                    {
                        SendSMSItem item = new SendSMSItem(contact, msg);
                        this._stackSMSItems.Enqueue(item);
                    }
                    //contact.
                }
                if ((this._stackSMSItems.Count > 0) && !this.sending)
                {
                    this.StartSend();
                }
            }

            return 1;
        }

        /// <summary>
        /// 通过手机号找用户
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public int findContactByMobileNo(string mobile)
        {
            if (mobile.Length != 11)
            {
                return -1;
            }
            for (int i = 0; i < _listContacts.Count; i++)
            {
                if (_listContacts[i].PersonalInfo.MobileNo == mobile)
                {
                    return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// 通过飞信号找用户
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        private int findContactBySID(string sid)
        {
            for (int i = 0; i < _listContacts.Count; i++)
            {
                if (_listContacts[i].Uri.Id == sid)
                {
                    return i;
                }
            }
            return -1;
        }
        /// <summary>
        /// 通过飞信号找手机号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string getMobileNo(string id)
        {
            if (_listContacts == null)
            {
                _listContacts = _contactBase.getAllContactList();
            }
            for (int i = 0; i < _listContacts.Count; i++)
            {
                if (_listContacts[i].Uri.Id == id)
                {
                    return _listContacts[i].PersonalInfo.MobileNo;
                }
            }
            //ErrorLog.WriteLog("无法找到该飞信号用户的手机号：" + id);
            return id;
        }
    }
}
